var Models = require('./db.js');
var express = require('express');
var router = express.Router();

/* GET home page. */
// router.get('/', function(req, res, next) {
//   res.render('index.ejs', { title: 'Ejs' });
// });
// 
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

router.route('/todoItems')
    .all((req, res, next) => {
        next();
    })
    .get((req, res, next) => {
      Models.Todo.find({})
            .exec((err, todolist) => {
                if (err) {
                    console.log(err);
                } else {
                    res.json(todolist);
                }
            });
    })
    .post((req, res) => {
        let newItem = req.body.newItem;
        console.log(newItem);
        Models.Todo.create(newItem, (err) => {
            if (err) {
                console.log('发生错误');
                console.log(err);
            } else {
                console.log('添加成功');
                Models.Todo.find({})
                    .exec((err, todolist) => {
                        if (err) {
                            console.log(err);
                        } else {
                            res.send(todolist);
                        }
                    });
            }
        })
    });

router.route('/todoItems/:id')
    .patch((req, res) => {
        let _id = req.params.id;
        Models.Todo.findOneAndUpdate({ _id: _id }, {
                $set: { 'done': true }
            }, { new: true })
            .then((result, err) => {
                console.log("更新");
                console.log(result);
                Models.Todo.find({})
                    .exec((err, todolist) => {
                        if (err) {
                            console.log(err);
                        } else {
                            res.send(todolist);
                        }
                    });
            })
            .catch(err => res.json(err));
    })
    .delete((req, res) => {
        let _id = req.params.id;
        Models.Todo.remove({ _id: _id })
            .then((result) => {
                console.log('删除成功！');
                console.log(result);
                Models.Todo.find({})
                    .exec((err, todolist) => {
                        if (err) {
                            console.log(err);
                        } else {
                            res.send(todolist);
                        }
                    });
            })
            .catch(err => res.json(err));
    })

router.get('/html', function(req, res, next) {
    res.json([{
        id: 1,
        username: 'api'
    }, {
        id: 2,
        username: 'html'
    }]);
});

router.get('/users', function(req, res, next) {
    res.json({ message: 'welcome to our api!!' });
});
module.exports = router;